from django import template
from django import forms
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from pirate_messages.models import Message
from django.db import transaction
from django.middleware import csrf
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import smart_str
from ajaxapi.views import clean_html
from pirate_core.views import template_for_model

import datetime
from pirate_signals.models import notification_send

from django.shortcuts import get_object_or_404

from pirate_core.views import HttpRedirectException, namespace_get

from customtags.decorators import block_decorator
register = template.Library()
block = block_decorator(register)

get_namespace = namespace_get('pp_messages')


@block
def pp_get_messages(context, nodelist, *args, **kwargs):
    
    context.push()
    namespace = get_namespace(context)

    user = kwargs.get('user', None)
    
    notes = Notification.objects.all()
    notes = notes.filter(receiver=user,is_read=False)
    count = len(list(notes))
    
    if count == 0: has_mail = False
    else: has_mail = True
    namespace['has_mail'] = has_mail
    namespace['count'] = count
    
    output = nodelist.render(context)
    context.pop()

    return output


@block
def pp_message_form(context, nodelist, *args, **kwargs):
    
    context.push()
    namespace = get_namespace(context)

    sender = kwargs.get('sender', None)
    receiver = kwargs.get('reciever', None)
    
    if POST and POST.get("form_id") == "pp_message_form":
        form = MessageForm(POST)
        if form.is_valid():   
            mes = Message(sender=sender,receiver=receiver,created_dt=datetime.datetime.now(),read=False,text=form['clean'])
            mes.save()
            c_type = ContentType.objects.get_for_model(sender)
            raise HttpRedirectException(HttpResponseRedirect("/user_profile.html?_t=" + str(c_type.pk) + "&_o=" + str(sender.pk)))
    else: form = MessageForm()
    
    namespace['form'] = form
    
    output = nodelist.render(context)
    context.pop()

    return output

class MessageForm(forms.ModelForm):
    """This form is used to create a subscription object between two users."""

    class Meta:
        model = Message
        exclude = ('read','sender','reciever',)

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="pp_message_form")
